package com.bokee.archerwq.lab.mina.client;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bokee.archerwq.lab.mina.message.Response;

/**
 * 
 * @author wangqiang
 * 
 */
public class TimeClientHandler extends IoHandlerAdapter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private Map<String, Object> waitMap = new ConcurrentHashMap<String, Object>();
	private Map<String, String> resultMap = new ConcurrentHashMap<String, String>();

	public TimeClientHandler(Map<String, Object> waitMap,
			Map<String, String> resultMap) {
		this.waitMap = waitMap;
		this.resultMap = resultMap;
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.error(cause.getClass().getName(), cause);
		session.close();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		Response response = (Response) message;
		logger.info("response detail:[" + response.getReqId() + "-"
				+ response.getDateTime() + "]");
		resultMap.put(response.getReqId(), response.getDateTime());
		Object waitObject = waitMap.get(response.getReqId());

		if (waitObject != null) {
			// activate the waiting operations on this object
			synchronized (waitObject) {
				waitObject.notify();
			}
		}
	}

}
